import store from '@/store'
import * as util from '@/utils/util'
import config from '@/core/config/index.js'
import {
	random
} from '@/uni_modules/uview-plus';
/**
 * 对象转url参数
 */
export const objParamsToUrl = (obj) => {

	if (obj && typeof obj === 'object') {
		let str = '?'
		for (let key in obj) {
			str += `${key}=${obj[key]}&`
		}
		return str.slice(0, -1)
	} else {
		console.log('传入obj为空或不是object');
	}
}
/**
 * url参数转对象
 * @param {string} url传入扫码进入options.scene   其它情况传入url后面的参数链接
 */
export const urlParamsToObj = (url) => {
	if (url && typeof url === 'string') {
		let obj = {}
		let decode = decodeURIComponent(url)
		let arr = []
		if (decode.includes('?')) {
			arr = decode.split('?')[1].split('&')
		} else {
			arr = decode.split('&')
		}
		arr.forEach(item => {
			let arr1 = item.split('=')
			obj[arr1[0]] = arr1[1]
		})
		return obj
	} else {
		console.log('传入url为空或不是string');
	}
}


export const getCurrentPageInfo = (data) => {
	var pages = getCurrentPages();
	var page = pages[pages.length - 1];
	return page
}
/**
 * 设置分享的数据
 * @param {Object} data:{title,path,imageUrl}  
 * @param {string} data.title: 转发的标题 （默认标题config中配置的标题）
 * @param {string} data.path: '/pages/home/index'
 * @param {string} data.imageUrl: ''
 * @param {Function} data.complete: ''
 */
export const setShareData = (data) => {
	console.log(data);
	let share = {
		title: data.title || config.get('name'), // 转发的标题 （默认标题）
		path: data.path || `/pages/home/index`, // 默认是当前页面，必须是以‘/’开头的完整路径
		//自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，
		//支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
		imageUrl: data.imageUrl || '',
		complete: data.complete || null
	}
	uni.setStorageSync('shareInfo', share)
}
/**
 * url参数转对象
 * @param {String} url 参数地址
 * @param {String} split1 分割符1
 * @param {String} split2 分割符2
 */
export const urlParmasToObject = (url = "https://www.baidu.com/?id=1&type=1", split1 = '&', split2 = '=') => {
	if (!url) return console.warn('未传入url');
	let parmas = '';
	if (url.includes('?')) parmas = url.split('?')[1];
	else parmas = url;
	const arr1 = parmas.split(split1).map(item => item.split(split2));
	const obj = {};
	arr1.forEach(item => obj[item[0]] = item[1]);
	return obj;
}
/**
 * uview的动画随机mode
 * @param {Number} index 索引
 */
export const getTransitionMode = (index = -1) => {
	const modeList = ['fade', 'fade-up', 'fade-down', 'fade-left', 'fade-right', 'slide-up', 'slide-down',
		'slide-left', 'slide-right'
	]
	let mode = modeList[0]
	if (index != -1) {
		mode = modeList[random(0, modeList.length - 1)]
	} else {
		mode = modeList[index % modeList.length - 1]
	}
	return mode
}
/**
 * 打开地图查看位置
 * @param {Object}  = options
 * options.lat  经度
 * options.lon  纬度
 * options.name  名字
 * options.address  地址
 * @param {Function}  = cb  
 */
export const openAddressMap = (options, cb) => {
	console.log(options);
	if (!options.lat && (!options.lon || !options.lng)) return console.warn('请传入经纬度');
	uni.openLocation({
		latitude: Number(options.lat),
		longitude: Number(options.lon || options.lng),
		name: options.name || '',
		address: options.address || '',
		complete: res => cb ? cb() : null,
	});
}
/**
 * 富文本图片格式化
 *  * @param {string}  路径 content:我是富文本内容
 */
export const formatRich = (content) => {
	let res = ''
	if (content) {
		res = content.replace(new RegExp('<img', 'gi'),
			"<img style='width:100%;vertical-align: middle;'")
		res = res.replace(new RegExp('<p', 'gi'),
			"<p style='word-break: break-all;'")
	}
	return res
}

/**
 * 非tabbar页面自定义事件跳转传参(注:刷新丢失)  
 * @param {boolean}  是否需要登录 isLogin:false
 * @param {string}  路径 url:'pages/home/index'
 * @param {string}  事件名 eventName:'sendData'
 * @param {object}  传参 eventData:{a:1}
 */
export const navToPageParams = (isLogin = false, url, eventName = '', eventData = {}) => {
	if (isLogin) {
		if (checkLogin()) {
			uni.navigateTo({
				url: `/${url}`,
				success: res => {
					res.eventChannel.emit(eventName, eventData)
				}
			})
		} else {
			navTo('pages/login/index')
		}
	} else {
		uni.navigateTo({
			url: `/${url}`,
			success: res => {
				res.eventChannel.emit(eventName, eventData)
			}
		})
	}
}
/**
 * 跳转传参
 * @param {boolean}  isLogin:true
 * @param {string}  path:''
 * @param {object}  params:{}
 * @param {Function}  cellback:()=>{}
 */
export const navToPage = (isLogin = false, path = '', params = {}, cellback) => {
	if (isLogin) {
		if (checkLogin()) {
			if (cellback) cellback()
			else navTo(path, params)
		} else {
			navTo('pages/login/index')
		}
	} else {
		if (cellback) cellback()
		else navTo(path, params)
	}
	return {
		isLogin,
		path,
		params,
		cellback
	}
}
/**
 * 图片预览,传入current:当前索引和urls图片列表
 * @param {Number} current:0  
 * @param {Array<string>|string}  urls:['']|''
 */
export const previewImage = async (current = 0, urls, showmenu = false) => {
	if (typeof urls == 'string') urls = [urls]
	uni.previewImage({
		current,
		urls,
		showmenu,
		loop: true,
	})

}
/**
 * 文本复制
 * @param {Number} data:'要复制的文本'
 */
export const copyText = (data, showToast = true) => {
	uni.setClipboardData({
		data,
		showToast,
	});
}
/**
 * 电话拨号
 * @param {string} phoneNumber:'15011111111'
 */
export const cellPhone = (phoneNumber, cb) => {
	uni.makePhoneCall({
		phoneNumber: String(phoneNumber),
		success: (res) => {
			if (cb) cb(res)
		}
	})
}
/**
 * 二次确认框
 * @param {String}  title - "标题"
 * @param {String}  content - "内容"
 * @param {Function}  confirm - 确认
 * @param {Function}  cancel - 取消
 */
export const showModel = (options) => {
	uni.showModal({
		title: options.title || '温馨提示',
		content: options.content,
		showCancel: options.showCancel || true,
		confirmText: options.confirmText || '确定',
		cancelText: options.cancelText || '取消',
		success(res) {
			if (res.confirm) {
				options.confirm && options.confirm();
			}
			if (res.cancel) {
				options.cancel && options.cancel();
			}
		}
	})
}

/**
 * 显示成功提示框
 */
export const showSuccess = (msg, duration = 1500, callback) => {
	uni.showToast({
		title: msg,
		icon: 'success',
		mask: true,
		duration,
		success() {
			callback && callback()
		}
	})
}

/**
 * 显示失败提示框
 */
export const showError = (msg, callback) => {
	uni.showModal({
		title: '友情提示',
		content: msg,
		showCancel: false,
		success(res) {
			callback && callback()
		}
	})
}

/**
 * 显示纯文字提示框
 */
export const showToast = (msg, icon = 'none', duration = 1500, mask = true) => {
	uni.showToast({
		title: msg, // 提示的内容
		icon,
		mask, // 是否显示透明蒙层，防止触摸穿透
		duration // 提示的延迟时间，单位毫秒，默认：1500
	})
}

/**
 * tabBar页面路径列表 (用于链接跳转时判断)
 * tabBarLinks为常量, 无需修改
 */
export const getTabBarLinks = () => {
	const tabBarLinks = [
		'pages/find-car/index',
		'pages/square/index',
		'pages/circle/index',
		'pages/service/index',
		'pages/user/index',
	]
	return tabBarLinks
}

/**
 * 生成转发的url参数(string格式)
 */
export const getShareUrlParams = (params) => {
	return util.urlEncode({
		refereeId: store.getters.userId, // 推荐人ID
		...params
	})
}

/**
 * 跳转到指定页面url
 * 支持tabBar页面
 * @param {string}  url   页面路径
 * @param {object}  query 页面参数
 * @param {string}  modo  跳转类型  默认:navigateTo) 可选:redirectTo
 */
export const navTo = (url, query = {}, modo = 'navigateTo') => {
	if (!url || url.length == 0) {
		return false
	}
	// tabBar页面, 使用switchTab
	if (util.inArray(url, getTabBarLinks())) {
		uni.switchTab({
			url: `/${url}`
		})
		return true
	}
	// 生成query参数
	const queryStr = query ? '?' + util.urlEncode(query) : ''
	// 普通页面, 使用navigateTo
	modo === 'navigateTo' && uni.navigateTo({
		url: `/${url}${queryStr}`,
	})
	// 特殊指定, 使用redirectTo
	modo === 'redirectTo' && uni.redirectTo({
		url: `/${url}${queryStr}`,
	})
	return true
}

/**
 * 退回页面
 * @param {integer}  page 页面数量
 */
export const navBack = (page = 1) => {
	uni.navigateBack({
		delta: page
	});
}

/**
 * 验证是否已登录
 */
export const checkLogin = () => {
	return !!store.getters.userId
}
/**
 * 获取用户信息
 */
export const getUserInfo = (key) => {
	let data = store.getters.userInfo
	if (key && data) {
		return data[key]
	} else {
		return data || false
	}
}
/**
 * 发起支付请求  微信小支付
 * @param {Object} 参数
 */
export const wxPayment = (option) => {
	const options = {
		timeStamp: '',
		nonceStr: '',
		prepay_id: '',
		paySign: '',
		...option
	}
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: options.timeStamp,
			nonceStr: options.nonceStr,
			'package': `prepay_id=${options.prepay_id}`,
			signType: 'MD5',
			paySign: options.paySign,
			success: res => resolve(res),
			fail: res => reject(res)
		})
	})
}


/**
 * 验证十进制数字
 */
export function testNumber(value) {
	return /^[\+-]?(\d+\.?\d*|\.\d+|\d\.\d+e\+\d+)$/.test(value)
}

/**
 * @description 用于获取用户传递值的px值  如果用户传递了"xxpx"或者"xxrpx"，取出其数值部分，如果是"xxxrpx"还需要用过uni.rpx2px进行转换
 * @param {number|string} value 用户传递值的px值
 * @param {boolean} unit 
 * @returns {number|string}
 */
export function getPx(value, unit = false) {
	if (testNumber(value)) {
		return unit ? `${value}px` : Number(value)
	}
	// 如果带有rpx，先取出其数值部分，再转为px值
	if (/(rpx|upx)$/.test(value)) {
		return unit ? `${uni.upx2px(parseInt(value))}px` : Number(uni.upx2px(parseInt(value)))
	}
	return unit ? `${parseInt(value)}px` : parseInt(value)
}

/**
 * @description 获取系统信息同步接口
 * @link 获取系统信息同步接口 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync 
 */
export function sys() {
	return uni.getSystemInfoSync()
}
export function getWindowInfo() {
	let ret = {}
	// #ifdef APP || H5 || MP-WEIXIN
	ret = uni.getWindowInfo()
	// #endif
	// #ifndef APP || H5 || MP-WEIXIN
	ret = sys()
	// #endif
	return ret
}
export function getDeviceInfo() {
	let ret = {}
	// #ifdef APP || H5 || MP-WEIXIN
	ret = uni.getDeviceInfo()
	// #endif
	// #ifndef APP || H5 || MP-WEIXIN
	ret = sys()
	// #endif
	return ret
}

/**
 * 获取NavBar高度
 * @param {Object} base
 */
export function getNavBarHeight(base = 0) {
	const baseHeight = getPx(base)
	const statusHeight = getWindowInfo().statusBarHeight;
	return baseHeight + statusHeight;
}

/**
 * 保存图片到相册
 * @param {String|Array} img 图片地址 可以传数组或字符串
 */
export function savePhotos(album) {
	const imgArr = []
	if (typeof album === 'string') {
		imgArr.push(album)
	}
	if (Array.isArray(album)) {
		imgArr.push(...album)
	}
	imgArr.forEach((item, index) => {
		uni.downloadFile({
			url: item,
			header: {
				'Authorization': 'Bearer ' + store.getters.token
			},
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveImageToPhotosAlbum({
						filePath: res.tempFilePath,
						success: (res) => {
							if (index === (imgArr.length - 1)) {
								showSuccess('保存成功！')
							}
						},
						fail: (err) => {
							console.error("文件保存失败：", err)
						}
					})
				}
			},
			fail: (err) => {
				console.error("文件下载失败：", err)
			}
		})
	})
}